package com.jichaoyun.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
//import com.jichaoyun.model.entity.Menu;
import com.jichaoyun.model.entity.Menu;
import com.jichaoyun.sys.mapper.MenuMapper;
import com.jichaoyun.sys.service.IMenuService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
* @author zhen
* @description 针对表【menu】的数据库操作Service实现
* @createDate 2023-11-10 15:12:13
*/
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {

    @Resource
    private MenuMapper menuMapper;

    @Override
    public List<Menu> getAllMenu() {
        LambdaQueryWrapper<Menu> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Menu::getParentId,0);
        List<Menu> menuList = this.baseMapper.selectList(lambdaQueryWrapper);
        setChildrenMenu(menuList);
        return menuList;
    }

    /**
     * 获取子菜单，用递归的方式
     * @param menuList
     */
    private void setChildrenMenu(List<Menu> menuList) {
        if(menuList != null) {
            for (Menu menu : menuList) {
                LambdaQueryWrapper<Menu> subQuery = new LambdaQueryWrapper<>();
                subQuery.eq(Menu::getParentId, menu.getMenuId());
                List<Menu> subMenuList = this.baseMapper.selectList(subQuery);
                menu.setChildren(subMenuList);
                setChildrenMenu(subMenuList);
            }
        }
    }

    /**
     * 根据用户id获取目录
     * @param userId
     * @return
     */
    @Override
    public List<Menu> getMenuListByUserId(Integer userId) {
        // 一级菜单
        List<Menu> menuList = this.getBaseMapper().getMenuListByUserId(userId, 0);
        // 子菜单
        setMenuChildrenByUserId(userId, menuList);
        return menuList;
    }

    private void setMenuChildrenByUserId(Integer userId, List<Menu> menuList) {
        if (menuList != null) {
            for (Menu menu : menuList) {
                List<Menu> subMenuList = this.getBaseMapper().getMenuListByUserId(userId, menu.getMenuId());
                menu.setChildren(subMenuList);
                // 递归
                setMenuChildrenByUserId(userId,subMenuList);
            }
        }
    }



}




